<template>
  <div>
    <el-dialog
      :title="mode==='add'?'新增规则':'编辑规则'"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="800px"
      center
      @close="close"
    >
      <!-- 表单 -->
      <div v-loading="loading" class="content">
        <el-form ref="ruleForm" :model="form" :rules="rules" label-width="100px" size="small">
          <!-- 消费金额 -->
          <el-form-item label="消费金额：" prop="amount">
            <el-input v-model.trim="form.amount" maxlength="10" class="input-append-350">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>

          <!--  赠送类型 -->
          <el-form-item label="赠送类型：" prop="awardTypeExtra" @cancel="awardTypeExtraChange">
            <el-checkbox-group v-model="form.awardTypeExtra">
              <el-checkbox label="bonusBalance">钱包余额</el-checkbox>
              <el-checkbox label="bonusPoint">积分</el-checkbox>
              <el-checkbox :disabled="form.awardTypeExtra.includes('bonusCoupon')" label="bonusCardCoupon">卡券
              </el-checkbox>
              <el-checkbox :disabled="form.awardTypeExtra.includes('bonusCardCoupon')" label="bonusCoupon">优惠券(已废弃)
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <!-- 余额 -->
          <el-form-item
            v-if="form.awardTypeExtra.includes('bonusBalance')"
            label="赠送余额："
            prop="balance"
          >
            <el-input
              v-model.trim="form.balance"
              placeholder="请输入"
              maxlength="10"
              class="input-append-350"
            >
              <template slot="append">元</template>
            </el-input>
          </el-form-item>

          <!-- 积分 -->
          <el-form-item
            v-if="form.awardTypeExtra.includes('bonusPoint')"
            label="赠送积分："
            prop="points"
          >
            <el-input v-model.trim="form.points" maxlength="7" class="input-append-350">
              <template slot="append">个</template>
            </el-input>
          </el-form-item>

          <!--          <el-form-item-->
          <!--            v-if="form.awardTypeExtra.includes('bonusCoupon')"-->
          <!--            label="送优惠券："-->
          <!--            prop="couponData"-->
          <!--          >-->
          <!--            <ul>-->
          <!--              <li v-for="(item,index) in form.couponData" :key="index">-->
          <!--                <el-card :body-style="{ padding: '0 20px' }" shadow="always" class="el-card-coupon">-->
          <!--                  <div class="coupon-list">-->
          <!--                    <el-form-item-->
          <!--                      :prop="'couponData.'+index+'.couponId'"-->
          <!--                      :rules="rules.couponAwardId"-->
          <!--                      style="display:inline-block"-->
          <!--                    >-->
          <!--                      <div class="coupon-info">-->
          <!--                        <div>券名：{{ item.name }}</div>-->
          <!--                      </div>-->
          <!--                    </el-form-item>-->
          <!--                    <div class="coupon-num">-->
          <!--                      <el-form-item-->
          <!--                        :prop="'couponData.'+index+'.num'"-->
          <!--                        :rules="rules.couponNum"-->
          <!--                        style="display:inline-block"-->
          <!--                      >-->
          <!--                        <el-input-number v-model="item.num" :min="1" :max="99"/>&nbsp;&nbsp;张&nbsp;&nbsp;-->
          <!--                      </el-form-item>-->
          <!--                      <el-button type="text" style="display:inline" @click="delCardCoupon(index)">删除</el-button>-->
          <!--                    </div>-->
          <!--                  </div>-->
          <!--                </el-card>-->
          <!--              </li>-->
          <!--            </ul>-->
          <!--            <el-button-->
          <!--              type="text"-->
          <!--              icon="el-icon-plus"-->
          <!--              style="display:block"-->
          <!--              @click="openCouponList"-->
          <!--            >增加券-->
          <!--            </el-button>-->
          <!--            <div style="color:#909399;font-size: 12px;">单次最多添加卡券种类不超过10种，卡券总数量不超过30张（因为微信限制，暂不支持配置微信商家券）</div>-->
          <!--          </el-form-item>-->

          <!--领券活动 规则类型-->
          <el-form-item
            v-if="form.awardTypeExtra.includes('bonusCardCoupon')||form.awardTypeExtra.includes('bonusCoupon')"
            :label="form.awardTypeExtra.includes('bonusCardCoupon')?'赠送卡券：':'送优惠券'"
            prop="couponData"
          >
            <el-table
              :data="form.couponData"
              border
              stripe
              size="small"
              empty-text="暂未配置"
              style="width: 800px"
            >
              <el-table-column prop="couponId" label="批次号" />
              <el-table-column prop="name" label="卡券名称" />
              <el-table-column prop="couponType" label="卡券类型">
                <template slot-scope="scope">
                  {{ $store.getters.cardCouponTypeKeyOptions[scope.row.couponType]||"--" }}
                </template>
              </el-table-column>
              <el-table-column prop="amount" label="数量" width="170px">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'couponData[' + scope.$index + '].num'"
                    :rules="rules.couponNum"
                  >
                    <el-input-number
                      v-model="scope.row.num"
                      :min="1"
                      :max="99"
                      maxlength="2"
                      label="数量"
                      style="margin-top: 18px"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="60">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    @click.native.prevent="delCardCoupon(scope.$index)"
                  >删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button
              v-if="form.awardTypeExtra.includes('bonusCardCoupon')"
              :disabled="form.couponData.length>=10"
              type="text"
              icon="el-icon-plus"
              style="display:block"
              @click.native.prevent="openDialogCardCouponTable"
            >增加卡券
            </el-button>
            <!--<el-button-->
            <!--  v-if="form.awardTypeExtra.includes('bonusCoupon')"-->
            <!--  :disabled="form.couponData.length>=10"-->
            <!--  type="text"-->
            <!--  icon="el-icon-plus"-->
            <!--  style="display:block"-->
            <!--  @click.native.prevent="openCouponList"-->
            <!--&gt;增加券-->
            <!--</el-button>-->
            <div style="color:#909399;font-size: 12px;">单次最多添加卡券种类不超过10种，卡券总数量不超过30张（因为微信限制，暂不支持配置微信商家券）</div>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" round @click="hide">取 消</el-button>
        <el-button size="small" round type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 弹框活动券 -->
    <dialog-coupon-list ref="dialogCouponList" />
    <!--券2.0 筛选表格 -->
    <DialogCardCouponTable ref="dialogCardCouponTable" :card-coupon-type="['cash','discount','exchange','cash_wx_pay','times','gift']" :has-checked-ids="hasCheckedCardCouponIds" />
  </div>
</template>

<script>
import DialogCouponList from '@/components/DialogCouponList'
import DialogCardCouponTable from '@/components/DialogCardCouponTable'
import {
  validateCustomTwoDecimal,
  validateCustomPositiveInt
} from '@/utils/validate.js'

export default {
  components: {
    DialogCouponList,
    DialogCardCouponTable
  },
  data() {
    /**
     * 表单校验方法相关
     */
    // 消费金钱校验
    const validateRmb = (rule, value, callback, text) => {
      if (value === '') {
        callback(new Error(text))
      } else if (!validateCustomTwoDecimal(value)) {
        callback(new Error('请输入0.01~99999.99范围金额（小数位不超过2位）'))
      } else {
        callback()
      }
    }

    // 权益规则 消费金额
    const validateBaseAmount = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入消费金额'))
      } else if (!validateCustomTwoDecimal(value)) {
        callback(new Error('请输入0.01~99999.99范围金额（小数位不超过2位）'))
      } else if (this.amountArr.includes(Number(value))) {
        callback(new Error('该消费金额规则已存在'))
      } else {
        callback()
      }
    }

    // 权益规则 赠送金额
    const validateBalance = (rule, value, callback) => {
      validateRmb(rule, value, callback, '请输入赠送余额金额')
    }

    // 权益规则 赠送积分
    const validatePoints = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入则送积分'))
      } else if (!validateCustomPositiveInt(value, 7)) {
        callback(new Error('请输入正整数'))
      } else {
        callback()
      }
    }

    // 赠送优惠券数量
    const validateCouponNum = (rule, value, callback) => {
      if (this.$isNull(value)) {
        callback('请输入数量')
      } else if (!validateCustomPositiveInt(value, 2)) {
        callback(new Error('请输入正整数'))
      } else {
        this.$refs.ruleForm.validateField(['couponData'])
        callback()
      }
    }

    // 奖励优惠券
    const validateCouponBonus = (rule, value, callback) => {
      if (!value.length) {
        callback('请至少选择一种')
      } else if (value.length > 10) {
        callback('卡券种类不超过10种')
      } else {
        let maxAmount = 0
        value.forEach(v => {
          if (validateCustomPositiveInt(v.num, 2)) {
            maxAmount += v.num
          }
        })
        if (maxAmount > 30) {
          callback('卡券总数量不超过30张')
        } else {
          callback()
        }
      }
    }

    return {
      /**
       * 表单校验字段相关
       */
      rules: {
        // 消费金额
        amount: [
          {
            required: true,
            validator: validateBaseAmount,
            trigger: ['blur', 'change']
          }
        ],
        // 如果有充送规则 至少设置一种充送奖励
        awardTypeExtra: [
          {
            type: 'array',
            required: true,
            message: '请至少设置一种充送奖励',
            trigger: 'change'
          }
        ],
        // 赠送金额
        balance: [
          {
            required: true,
            validator: validateBalance,
            trigger: ['blur', 'change']
          }
        ],
        // 积分
        points: [
          {
            required: true,
            validator: validatePoints,
            trigger: ['blur', 'change']
          }
        ],
        // 优惠券
        couponData: [
          {
            type: 'array',
            required: true,
            validator: validateCouponBonus,
            trigger: ['blur', 'change']
          }
        ],
        // 优惠券数量
        couponNum: [
          {
            required: true,
            validator: validateCouponNum,
            trigger: ['blur', 'change']
          }
        ]
      },
      // 配置
      resolve: null,
      reject: null,
      // 状态
      dialogVisible: null,
      loading: false,
      // 数据
      mode: 'add',
      hasCheckedCardCouponIds: [],
      amountArr: [],
      form: {
        calculateType: 1,
        amount: '',
        balance: '',
        points: '',
        couponData: [],
        awardTypeExtra: []
      }
    }
  },
  methods: {
    open({ mode = 'add', calculateType = 1, row, amountArr = [] }) {
      this.mode = mode
      this.amountArr = amountArr
      if (this.mode === 'edit') {
        this.form = Object.assign({}, row)
      } else {
        this.form.calculateType = calculateType
      }
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
    },

    close() {
      this.loading = false
      this.hasCheckedCardCouponIds = []
      this.form = {
        calculateType: 1,
        amount: '',
        balance: '',
        points: '',
        couponData: [],
        awardTypeExtra: []
      }
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields()
      })
    },

    hide() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
    },

    submit() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.resolve && this.resolve(Object.assign({}, this.form))
          this.hide()
        }
      })
    },

    /**
     *  按钮组
     */
    // 删除优惠券
    delCardCoupon(index) {
      this.form.couponData.splice(index, 1)
    },

    // 新增优惠券
    openCouponList() {
      this.hasCheckedCardCouponIds = []
      this.form.couponData.forEach(v => {
        this.hasCheckedCardCouponIds.push(v.couponId)
      })
      this.$refs.dialogCouponList.open(this.hasCheckedCardCouponIds, 2).then(res => {
        this.$refs.ruleForm.clearValidate(['couponData'])
        const params = Object.assign({}, res)
        params.num = res.amount
        params.name = res.couponName
        this.form.couponData.push(params)
      })
    },

    // 新增卡券
    openDialogCardCouponTable() {
      this.hasCheckedCardCouponIds = []
      this.form.couponData.forEach(v => {
        this.hasCheckedCardCouponIds.push(v.couponId)
      })
      this.$refs.dialogCardCouponTable.open().then(res => {
        this.$refs.ruleForm.clearValidate(['couponData'])
        res.forEach(v => {
          v.name = v.couponName
          v.num = v.amount
          delete v.amount
          delete v.couponName
        })
        this.form.couponData.push(...JSON.parse(JSON.stringify(res)))
      })
    },

    /**
     * 状态
     */
    // 赠送类型
    awardTypeExtraChange(val) {
      if (!val.includes('bonusCoupon') && !val.includes('bonusCardCoupon')) {
        this.form.couponData = []
      }
    }

  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
/* input */
.input-append-350 {
  width: 350px;
}

/* 券列表 */
//.el-card-coupon {
//  width: 100%;
//  margin-bottom: 10px;
//}

//.coupon-list {
//  margin-top: 18px;
//  width: 100%;
//  display: flex;
//  align-items: center;
//  justify-content: space-between;
//
//  .coupon-info {
//    color: #606266;
//    margin-right: 20px;
//    line-height: 1.2;
//  }
//}
</style>
